import { router } from '@/router'
import { DEFAULT_OPENED, HOME_PATH } from '@/setting'

const state = {
  opened: [],
  current: ''
}

const mutations = {
  init (state, { opened, home }) {
    state.opened = opened
    state.current = home
  },
  add (state, page) {
    state.opened.push(page)
  },
  remove (state, { index, deleteCount = 1 }) {
    state.opened.splice(index, deleteCount)
  },
  setCurrent (state, current) {
    state.current = current
  }
}

const actions = {
  /**
   * 初始话页面
   * @param commit
   */
  init ({ commit }) {
    // TODO 若存在缓存，则从缓存中初始化
    commit('init', { opened: DEFAULT_OPENED, home: HOME_PATH })
  },
  openPage ({ state, commit }, { name, fullPath, query, params, meta, redirectedFrom }) {
    if (!state.opened.find(page => page.fullPath === fullPath)) {
      const page = { name, fullPath, query, params, meta, redirectedFrom }
      if (fullPath !== '/' && !meta.hidden) {
        commit('add', page)
      }
    }
    commit('setCurrent', fullPath)
  },
  /**
   * 关闭页面
   * @param state
   * @param commit
   * @param fullPath
   */
  closePage ({ state, commit }, fullPath) {
    const opened = state.opened
    let closeIndex = -1
    opened.find((page, index) => {
      if (page.fullPath === fullPath) {
        closeIndex = index
        return true
      }
      return false
    })
    commit('remove', { index: closeIndex })
    if (fullPath === state.current) {
      closeIndex = closeIndex === state.opened.length ? closeIndex - 1 : closeIndex
      const newFullPath = opened[closeIndex].fullPath
      router.push(newFullPath).catch()
    }
  },
  closeAll ({ state, commit }) {
    const opened = state.opened
    commit('remove', { index: 1, deleteCount: opened.length - 1 })
    router.push(HOME_PATH).catch()
  },
  closeLeft ({ state, commit }) {
    let index = -1
    state.opened.find((page, i) => {
      const result = page.fullPath === state.current
      if (result) {
        index = i
      }
      return result
    })
    if (index > -1) {
      commit('remove', { index: 1, deleteCount: index - 1 })
    }
  },
  closeRight ({ state, commit }) {
    let index = -1
    state.opened.find((page, i) => {
      const result = page.fullPath === state.current
      if (result) {
        index = i
      }
      return result
    })
    if (index > -1) {
      commit('remove', { index: index + 1, deleteCount: state.opened.length - index })
    }
  },
  closeOther ({ state, commit }) {
    const opened = state.opened
    for (const i in opened) {
      if (opened[i].fullPath === state.current || opened[i].fullPath === HOME_PATH) {
        continue
      }
      commit('remove', { index: i })
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
